/**
 * C Implementation: grib_print_data
 *
 * Description:
 * prints all the data contained in a GRIB file
 * 
 * 附加1: 获取最大、最小、平均值
 * 附加2: 从数据值访问特定元素的示例
 *
 */
#include <stdio.h>
#include <stdlib.h>

#include "eccodes.h"

static void usage(const char* prog)
{
    printf("usage: %s filename\n", prog);
    exit(1);
}

int sfx_grib_print_data()
{
    int err = 0;

    const char* filename = "d:/sfxData/ECMWF/eccodes_test_data/regular_latlon_surface.grib1";

    FILE* in = fopen(filename, "rb");

    // create new handle from a message in a file
    codes_handle* h = codes_handle_new_from_file(0, in, PRODUCT_GRIB, &err);

    // get the size of the values array
    size_t values_len = 0;
    CODES_CHECK(codes_get_size(h, "values", &values_len), 0);
    double* values = (double*)malloc(values_len * sizeof(double));

    // get data values
    CODES_CHECK(codes_get_double_array(h, "values", values, &values_len), 0);

    for (int i = 0; i < values_len; i++) {
        printf("%d  %.10e\n", i, values[i]);
    }

    free(values);

    // 获取最大、最小、平均值
    double maxv, minv, average;
    CODES_CHECK(codes_get_double(h, "max", &maxv), 0);
    CODES_CHECK(codes_get_double(h, "min", &minv), 0);
    CODES_CHECK(codes_get_double(h, "average", &average), 0);

    printf("%d values found in %s\n", (int)values_len, filename);
    printf("max=%.10e min=%.10e average=%.10e\n", maxv, minv, average);

    {
        // Example of accessing specific elements from data values
        // 从数据值访问特定元素的示例
        double vals_arr[3] = { 0, 0, 0 };
        const int NUM      = 3;
        int index_arr[3];
        index_arr[0] = 0;               // first element
        index_arr[1] = values_len / 2;  // middle element (中位数)
        index_arr[2] = values_len - 1;  // last element

        CODES_CHECK(codes_get_double_elements(h, "values", index_arr, NUM, vals_arr), 0);
        for (int i = 0; i < NUM; ++i) {
            printf("value at index %d = %.10e\n", index_arr[i], vals_arr[i]);
        }
    }

    // free memory
    codes_handle_delete(h);
    fclose(in);
    return 0;
}
